package com.wyp168.leetcode;

import java.util.Arrays;

/**
 * @ClassName SearchRangeSolution
 * @Title TODO leetcode 31. 在一个排序数组中查找指定的元素第一次和最后一次出现的位置
 * @Description TODO
 * @Author wyp168
 * @Date 2022/10/8 22:24
 */
public class SearchRangeSolution {
    public static void main(String[] args) {
        SearchRangeSolution solution = new SearchRangeSolution();
        int[] nums = {5,7,7,8,8,10};
        int target = 8;
        int[] ints = solution.searchRange(nums, target);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }

    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        Arrays.fill(result, -1);
        searchNumRange(nums, target, 0, nums.length - 1, result);
        return result;
    }

    public void searchNumRange(int[] nums, int target, int left, int right, int[] result) {

        if (left < 0 || right < 0 || left > right) {
            return;
        }
        int mid = (left + right) / 2;
        if (nums[mid] == target) {
            if (result[0] == -1 || mid < result[0]) {
                result[0] = mid;
            }
            if (mid > result[1]) {
                result[1] = mid;
            }
        }
        searchNumRange(nums, target, left, mid - 1, result);
        searchNumRange(nums, target, mid + 1, right, result);
    }
}
